package com.yeyks.common.utils;

import com.yeyks.common.constants.HttpConstants;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

/**
 * @author fuchangshuai
 * @time 2018/12/26
 */
@Slf4j
public class OkHttpUtil {

    public static String get(OkHttpClient okHttpClient, String url) {
        Request request = new Request.Builder().url(url).build();
        try {
            okhttp3.Response response = okHttpClient.newCall(request).execute();
            return response.body().string();

        } catch (Exception e) {
            log.error("http get 接口失败 case: {}", Throwables.getStackTraceAsString(e));
        }
        return null;
    }

    public static String get(OkHttpClient okHttpClient, String url, String cookie) {
        Request request = new Request.Builder().url(url).addHeader("Cookie", cookie).build();
        try {
            okhttp3.Response response = okHttpClient.newCall(request).execute();
            return response.body().string();

        } catch (Exception e) {
            log.error("http get 接口失败 case: {}", Throwables.getStackTraceAsString(e));
        }
        return null;
    }

    public static String post(OkHttpClient okHttpClient, String url, String jsonData) {
        try {
            RequestBody body = RequestBody.create(HttpConstants.JSON, jsonData);
            Request request = new Request.Builder().url(url).post(body).build();

            okhttp3.Response response = okHttpClient.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            log.error("http post 接口失败 case: {}", Throwables.getStackTraceAsString(e));
            return null;
        }
    }

    public static String post(OkHttpClient okHttpClient, String url, String jsonData, String cookie) {
        try {
            RequestBody body = RequestBody.create(HttpConstants.JSON, jsonData);
            Request request = new Request.Builder().url(url)
                    .addHeader("Cookie", cookie).post(body).build();

            okhttp3.Response response = okHttpClient.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            log.error("http post 接口失败 case: {}", Throwables.getStackTraceAsString(e));
            return null;
        }
    }

}
